package com.ruoyi.compensationManagement.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.calculationSalary.service.CalculationSalaryService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MapConvertUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.compensationManagement.domain.*;
import com.ruoyi.compensationManagement.domain.vo.CompensationStaffPayrollVo;
import com.ruoyi.compensationManagement.domain.vo.SalaryFileVo;
import com.ruoyi.compensationManagement.domain.vo.StaffPayrollImportVo;
import com.ruoyi.compensationManagement.service.*;
import com.ruoyi.core.service.AttendanceCalculationService;
import com.ruoyi.system.domain.SysUserPositionLevelHistory;
import com.ruoyi.system.domain.SysUserSalaryHistory;
import com.ruoyi.system.service.ISysCommonService;
import com.ruoyi.system.service.ISysUserPositionLevelHistoryService;
import com.ruoyi.system.service.ISysUserSalaryHistoryService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import jdk.nashorn.internal.runtime.Context;
import org.apache.poi.hpsf.Decimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.compensationManagement.mapper.CompensationStaffpayrollMapper;

/**
 * 工资表Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-09
 */
@Service
public class CompensationStaffpayrollServiceImpl implements ICompensationStaffpayrollService {
    @Autowired
    private CompensationStaffpayrollMapper compensationStaffpayrollMapper;

    @Autowired
    private ICompensationDeductionAmountSettingsService compensationDeductionAmountSettingsService;

    @Autowired
    private ISysCommonService sysCommonService;

    @Autowired
    private CalculationSalaryService calculationSalaryService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ICompensationStaffPayrollLogService compensationStaffPayrollLogService;

    @Autowired
    private AttendanceCalculationService attendanceCalculationService;

    @Autowired
    private IPositionSettingsService positionSettingsService;
    @Autowired
    private ICompensationSalarySettingService compensationSalarySettingService;
    @Autowired
    private ISysUserSalaryHistoryService sysUserSalaryHistoryService;
    @Autowired
    private ISysUserPositionLevelHistoryService sysUserPositionLevelHistoryService;

    private static final Logger log = LoggerFactory.getLogger(CompensationStaffpayrollServiceImpl.class);

    /**
     * 查询工资表
     *
     * @param staffpayrollId 工资表主键
     * @return 工资表
     */
    @Override
    public CompensationStaffpayroll selectCompensationStaffpayrollByStaffpayrollId(Long staffpayrollId) {
        CompensationStaffpayroll compensationStaffpayroll = compensationStaffpayrollMapper.selectCompensationStaffpayrollByStaffpayrollId(staffpayrollId);
        compensationStaffpayroll.setDeductionsPartSql(JSON.parseArray(compensationStaffpayroll.getDeductionsPart(), CompensationDeductionAmountSettings.class));
        compensationStaffpayroll.setDeductionsPart(null);
        return compensationStaffpayroll;
    }

    /**
     * 查询工资表列表
     *
     * @param compensationStaffpayroll 工资表
     * @return 工资表
     */
    @Override
    public List<CompensationStaffpayroll> selectCompensationStaffpayrollList(CompensationStaffpayroll compensationStaffpayroll) {
        return compensationStaffpayrollMapper.selectCompensationStaffpayrollList(compensationStaffpayroll);
    }

    /**
     * 新增工资表
     *
     * @param compensationStaffpayroll 工资表
     * @return 结果
     */
    @Override
    public int insertCompensationStaffpayroll(CompensationStaffpayroll compensationStaffpayroll) {
        compensationStaffpayroll.setAuditStatus("N");
        return compensationStaffpayrollMapper.insertCompensationStaffpayroll(compensationStaffpayroll);
    }

    /**
     * 修改工资表
     *
     * @param compensationStaffpayroll 工资表
     * @return 结果
     */
    @Override
    public int updateCompensationStaffpayroll(CompensationStaffpayroll compensationStaffpayroll) {
        //将浮动项目数组对象转换为字符串存储数据库
        compensationStaffpayroll.setDeductionsPart(JSON.toJSONString(compensationStaffpayroll.getDeductionsPartSql()));
        //从数据库拿旧记录
        CompensationStaffpayroll old = selectCompensationStaffpayrollByStaffpayrollId(compensationStaffpayroll.getStaffpayrollId());
        //利用StringBuilder收集数据
        StringBuilder builder = new StringBuilder();

        if (old.getPositionSalary().compareTo(compensationStaffpayroll.getPositionSalary()) != 0) {
            builder.append("【岗位工资】：由" + old.getPositionSalary() + "改动为==>" + compensationStaffpayroll.getPositionSalary());
            builder.append("\n");
        }
        if (old.getPayWages().compareTo(compensationStaffpayroll.getPayWages()) != 0) {
            builder.append("【薪级工资】：由" + old.getPayWages() + "改动为==>" + compensationStaffpayroll.getPayWages());
            builder.append("\n");
        }
        if (old.getBasicPerformancePay().compareTo(compensationStaffpayroll.getBasicPerformancePay()) != 0) {
            builder.append("【基础性绩效工资】：由" + old.getBasicPerformancePay() + "改动为==>" + compensationStaffpayroll.getBasicPerformancePay());
            builder.append("\n");
        }
        if (old.getIncentivizedPerformancePay().compareTo(compensationStaffpayroll.getIncentivizedPerformancePay()) != 0) {
            builder.append("【奖励性绩效工资】：由" + old.getIncentivizedPerformancePay() + "改动为==>" + compensationStaffpayroll.getIncentivizedPerformancePay());
            builder.append("\n");
        }
        if (old.getBasicPerformanceAward().compareTo(compensationStaffpayroll.getBasicPerformanceAward()) != 0) {
            builder.append("【基础性绩效奖】：由" + old.getBasicPerformanceAward() + "改动为==>" + compensationStaffpayroll.getBasicPerformanceAward());
            builder.append("\n");
        }
        if (old.getOneChildCare().compareTo(compensationStaffpayroll.getOneChildCare()) != 0) {
            builder.append("【独生子女保健】：由" + old.getOneChildCare() + "改动为==>" + compensationStaffpayroll.getOneChildCare());
            builder.append("\n");
        }
        if (old.getHousingSubsidies().compareTo(compensationStaffpayroll.getHousingSubsidies()) != 0) {
            builder.append("【住房补贴】：由" + old.getHousingSubsidies() + "改动为==>" + compensationStaffpayroll.getHousingSubsidies());
            builder.append("\n");
        }
        if (old.getOvertimePay().compareTo(compensationStaffpayroll.getOvertimePay()) != 0) {
            builder.append("【加班工资】：由" + old.getOvertimePay() + "改动为==>" + compensationStaffpayroll.getOvertimePay());
            builder.append("\n");
        }

        //循环后端从数据库查到的浮动项与前端传进来的浮动项比较值是否相等
        for (CompensationDeductionAmountSettings oldFloat : old.getDeductionsPartSql()) {
            for (CompensationDeductionAmountSettings newFloat : compensationStaffpayroll.getDeductionsPartSql()) {
                if (newFloat.getId().longValue() == oldFloat.getId().longValue()) {
                    //浮动项新旧值不相等
                    if (newFloat.getCost().compareTo(oldFloat.getCost()) != 0) {
                        builder.append("【" + newFloat.getDeductionsType() + "】" + "：由" + oldFloat.getCost() + "改动为==>" + newFloat.getCost());
                        builder.append("\n");
                    }
                }
            }
        }

        if (old.getWagesPayable().compareTo(compensationStaffpayroll.getWagesPayable()) != 0) {
            builder.append("【应发工资】：由" + old.getWagesPayable() + "改动为==>" + compensationStaffpayroll.getWagesPayable());
            builder.append("\n");
        }
        if (old.getActualDeduction().compareTo(compensationStaffpayroll.getActualDeduction()) != 0) {
            builder.append("【实扣数】：由" + old.getActualDeduction() + "改动为==>" + compensationStaffpayroll.getActualDeduction());
            builder.append("\n");
        }
        if (old.getActualSalary().compareTo(compensationStaffpayroll.getActualSalary()) != 0) {
            builder.append("【实发数】：由" + old.getActualSalary() + "改动为==>" + compensationStaffpayroll.getActualSalary());
            builder.append("\n");
        }

        CompensationStaffPayrollLog compensationStaffPayrollLog = new CompensationStaffPayrollLog();
        compensationStaffPayrollLog.setStaffpayrollId(compensationStaffpayroll.getStaffpayrollId());
        compensationStaffPayrollLog.setLogInfo(builder.toString());
        compensationStaffPayrollLog.setLogDate(new Date());
        compensationStaffPayrollLogService.insertCompensationStaffPayrollLog(compensationStaffPayrollLog);
        return compensationStaffpayrollMapper.updateCompensationStaffpayroll(compensationStaffpayroll);
    }

    /**
     * 批量删除工资表
     *
     * @param staffpayrollIds 需要删除的工资表主键
     * @return 结果
     */
    @Override
    public int deleteCompensationStaffpayrollByStaffpayrollIds(Long[] staffpayrollIds) {
        return compensationStaffpayrollMapper.deleteCompensationStaffpayrollByStaffpayrollIds(staffpayrollIds);
    }

    /**
     * 删除工资表信息
     *
     * @param staffpayrollId 工资表主键
     * @return 结果
     */
    @Override
    public int deleteCompensationStaffpayrollByStaffpayrollId(Long staffpayrollId) {
        return compensationStaffpayrollMapper.deleteCompensationStaffpayrollByStaffpayrollId(staffpayrollId);
    }

    /**
     * 根据工号获取工资表信息
     */
    @Override
    public Map<String, Object> getPayrollInformationByJobNumber(String jobNumber, Date date) {
        HashMap<String, Object> map = new HashMap<>();
        //根据工号获取User对象
        SysUser user = sysUserService.getSysUserByJobNumber(jobNumber);
        if (user != null) {
            //姓名
            map.put("nickName", user.getNickName());
            //员工类型
            map.put("employeeType", user.getEmployeeType());
            //历史岗位等级对象
            SysUserPositionLevelHistory sysUserPositionLevelHistory = sysUserPositionLevelHistoryService.getPositionsByUserIdAndNowDate(user.getUserId(), date);
            //历史岗位信息对象
            PositionSettings positionSetting = positionSettingsService.selectPositionSettingsByPositionId(sysUserPositionLevelHistory.getPositionId());
            //历史薪级等级对象
            SysUserSalaryHistory userSalaryHistory = sysUserSalaryHistoryService.getSalaryHistoryByUserIdAndNowDate(user.getUserId(), date);
            //历史薪级信息对象
            CompensationSalarySetting compensationSalarySetting = compensationSalarySettingService.selectCompensationSalarySettingByPayId(userSalaryHistory.getPayId());

            //岗位名称
            Long parentId = positionSetting.getParentId();
            map.put("position", positionSettingsService.selectPositionSettingsByPositionId(parentId).getJobCategory());
            //薪级名称
            map.put("salary", compensationSalarySetting.getPayLevel());
            //薪级工资
            map.put("positionSalary", compensationSalarySetting.getPayWages());
            //岗位工资、基础性绩效工资、奖励性绩效工资、基础性绩效奖
            map.put("positionSalaryInfo", positionSetting);

            //加班费
            map.put("overtimePay", calculateOvertimePay(calculationSalaryService.workOvertime(user.getUserId(), date)));

            /*=========================扣款部分========================*/
            //遍历循环扣款金额设置表
            CompensationDeductionAmountSettings compensationDeductionAmountSettings = new CompensationDeductionAmountSettings();
            if (user.getEmployeeType().equals("在编人员")){
                compensationDeductionAmountSettings.setZbExecute("1");
            }
            if (user.getEmployeeType().equals("聘用人员")){
                compensationDeductionAmountSettings.setPyExecute("1");
            }
            List<CompensationDeductionAmountSettings> listDeductionAmountSettings = compensationDeductionAmountSettingsService.selectCompensationDeductionAmountSettingsList(compensationDeductionAmountSettings);


            //哺乳假扣款

            BigDecimal lactationLeave = new BigDecimal("0");
            if (attendanceCalculationService.getBreastFeedingLeaveHourForMonth(user.getUserId(), DateUtils.parseDateToStr("yyyy-MM", date)) > 0) {
                lactationLeave = calculateLessen(calculationSalaryService.lactationLeave(user.getUserId(), date));
            }
            map.put("lactationLeave", lactationLeave);

            //事假扣款
            BigDecimal compassionateLeave = new BigDecimal(String.valueOf(calculateLessen(calculationSalaryService.compassionateLeave(user.getUserId(), date))));
            map.put("compassionateLeave", compassionateLeave);
            //病假扣款
            BigDecimal sickLeave = new BigDecimal(String.valueOf(calculateLessen(calculationSalaryService.sickLeave(user.getUserId(), date))));
            map.put("sickLeave", sickLeave);

            //应发工资
            BigDecimal wagesPayable = new BigDecimal("0");
            wagesPayable=wagesPayable.add(positionSetting.getPositionSalary());
            wagesPayable=wagesPayable.add(positionSetting.getBasicPerformancePay());
            wagesPayable=wagesPayable.add(positionSetting.getIncentivizedPerformancePay());
            wagesPayable=wagesPayable.add(positionSetting.getBasicPerformanceAward());
            wagesPayable=wagesPayable.add(compensationSalarySetting.getPayWages());
            wagesPayable=wagesPayable.add(calculateOvertimePay(calculationSalaryService.workOvertime(user.getUserId(), date)));
            //数据回放便于存储
            for (CompensationDeductionAmountSettings listDeductionAmountSetting : listDeductionAmountSettings) {
                //是比率用应发工资*比率
                if (listDeductionAmountSetting.getIsRate().equals("Y")) {
                    BigDecimal bigDecimal = new BigDecimal("0");
                    BigDecimal rateM = new BigDecimal("0.01");
                    BigDecimal rate = listDeductionAmountSetting.getRate();
                    rate = rate.multiply(rateM);
                    bigDecimal = bigDecimal.add(wagesPayable.multiply(rate));
                    //四舍五入
                    bigDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
                    //把数据放回json方便读写
                    listDeductionAmountSetting.setCost(bigDecimal);
                }

                if (("扣哺乳假工资").equals(listDeductionAmountSetting.getDeductionsType())) {
                    listDeductionAmountSetting.setCost(lactationLeave);
                } else if (("扣事假工资").equals(listDeductionAmountSetting.getDeductionsType())) {
                    listDeductionAmountSetting.setCost(compassionateLeave);
                } else if (("扣病假工资").equals(listDeductionAmountSetting.getDeductionsType())) {
                    listDeductionAmountSetting.setCost(sickLeave);
                }
            }

            //浮动扣款项
            map.put("listDeductionAmountSettings", listDeductionAmountSettings);

        }
        return map;
    }

    /**
     * 确定工资表
     */
    @Override
    public int determiningStaffPayroll(CompensationStaffpayroll compensationStaffpayroll) {
        return compensationStaffpayrollMapper.determiningStaffPayroll(compensationStaffpayroll);
    }

    /**
     * 查询工资条
     *
     * @param compensationStaffpayroll
     * @return
     */
    @Override
    public List<CompensationStaffPayrollVo> selectCompensationStaffpayrollListToConvert(CompensationStaffpayroll compensationStaffpayroll) {
        List<CompensationStaffPayrollVo> compensationStaffPayrollVoList = compensationStaffpayrollMapper.selectCompensationArticleWageList(compensationStaffpayroll);
        compensationStaffPayrollVoList = compensationStaffPayrollVoList != null && compensationStaffPayrollVoList.size() > 0 ? compensationStaffPayrollVoList.stream().map(compensationStaffPayrollVo -> {
            //转换json
            List<CompensationDeductionAmountSettings> compensationDeductionAmountSettingsList = JSON.parseArray(compensationStaffPayrollVo.getDeductionsPart(), CompensationDeductionAmountSettings.class);
            compensationStaffPayrollVo.setCompensationDeductionAmountSettingsList(compensationDeductionAmountSettingsList);
            return compensationStaffPayrollVo;
        }).collect(Collectors.toList()) : new ArrayList<>();
        return compensationStaffPayrollVoList;
    }

    /**
     * 查询工资档案信息
     *
     * @param compensationStaffpayroll
     * @return
     */
    @Override
    public List<SalaryFileVo> selectCompensationStaffpayrollListToConvertSalaryFiles(CompensationStaffpayroll compensationStaffpayroll) {
        List<SalaryFileVo> salaryFileVoList = compensationStaffpayrollMapper.selectCompensationStaffpayrollListToConvertSalaryFiles(compensationStaffpayroll);

        salaryFileVoList = salaryFileVoList != null && salaryFileVoList.size() > 0 ? salaryFileVoList.stream().map(salaryFileVo -> {
            double v = salaryFileVo.getPositionSalary().doubleValue() + salaryFileVo.getPayWages().doubleValue() + salaryFileVo.getBasicPerformancePay().doubleValue() + salaryFileVo.getIncentivizedPerformancePay().doubleValue() + salaryFileVo.getBasicPerformancePay().doubleValue();
            BigDecimal bigDecimal = new BigDecimal(v + "");
            bigDecimal.setScale(2);
            salaryFileVo.setTotalWageBase(bigDecimal);
            salaryFileVo.setCompensationDeductionAmountSettingsList(JSON.parseArray(salaryFileVo.getDeductionsPart(), CompensationDeductionAmountSettings.class));
            return salaryFileVo;
        }).collect(Collectors.toList()) : new ArrayList<>();

        return salaryFileVoList;
    }

    @Override
    public String importStaffPayroll(List<StaffPayrollImportVo> staffPayrollList) {
        if (StringUtils.isNull(staffPayrollList) || staffPayrollList.size() == 0) {
            throw new ServiceException("导入工资数据不能为空！");
        }
        int totalNum = staffPayrollList.size();
        int Num = 2;
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        List<CompensationDeductionAmountSettings> listDeductionAmountSettingsCpoy = compensationDeductionAmountSettingsService.selectCompensationDeductionAmountSettingsList(new CompensationDeductionAmountSettings());
        for (StaffPayrollImportVo staffPayrollImportVo : staffPayrollList) {
            try {
                /*将数据存入工资表对象 计算工资存储进数据库*/
                CompensationStaffpayroll compensationStaffpayroll = new CompensationStaffpayroll();
                if (staffPayrollImportVo.getNickName() == null || staffPayrollImportVo.getNickName().equals("")) {
                    failureNum++;
                    failureMsg.append("<br/>" + "第" + Num + "行,姓名未填");
                    Num++;
                    continue;
                }
                if (staffPayrollImportVo.getJobnumber() == null || staffPayrollImportVo.getJobnumber().equals("")) {
                    failureNum++;
                    failureMsg.append("<br/>" + "第" + Num + "行,工号未填");
                    Num++;
                    continue;
                }
                if (staffPayrollImportVo.getEmployeeType() == null || staffPayrollImportVo.getEmployeeType().equals("")) {
                    failureNum++;
                    failureMsg.append("<br/>" + "第" + Num + "行,员工类型未填");
                    Num++;
                    continue;
                }
                if (staffPayrollImportVo.getSalaryyearmonth() == null || staffPayrollImportVo.getSalaryyearmonth().equals("")) {
                    failureNum++;
                    failureMsg.append("<br/>" + "第" + Num + "行,工资年月未填");
                    Num++;
                    continue;
                }
                if (staffPayrollImportVo.getPosition() == null || staffPayrollImportVo.getPosition().equals("")) {
                    failureNum++;
                    failureMsg.append("<br/>" + "第" + Num + "行,岗位名称未填");
                    Num++;
                    continue;
                }
                if (staffPayrollImportVo.getSalary() == null || staffPayrollImportVo.getSalary().equals("")) {
                    failureNum++;
                    failureMsg.append("<br/>" + "第" + Num + "行,薪级名称未填");
                    Num++;
                    continue;
                }
                SysUser sysUserByJobNumber = sysUserService.getSysUserByJobNumber(staffPayrollImportVo.getJobnumber());
                if (sysUserByJobNumber == null) {
                    failureNum++;
                    failureMsg.append("<br/>" + "第" + Num + "行,系统中无工号为："+staffPayrollImportVo.getJobnumber()+"的员工");
                    Num++;
                    continue;
                }

                compensationStaffpayroll.setJobnumber(staffPayrollImportVo.getJobnumber());
                compensationStaffpayroll.setNickName(staffPayrollImportVo.getNickName());
                compensationStaffpayroll.setEmployeeType(staffPayrollImportVo.getEmployeeType());
                compensationStaffpayroll.setSalaryyearmonth(staffPayrollImportVo.getSalaryyearmonth());
                compensationStaffpayroll.setPosition(staffPayrollImportVo.getPosition());
                compensationStaffpayroll.setSalary(staffPayrollImportVo.getSalary());

                //应发工资
                compensationStaffpayroll.setPositionSalary(staffPayrollImportVo.getPositionSalary());
                compensationStaffpayroll.setPayWages(staffPayrollImportVo.getPayWages());
                compensationStaffpayroll.setBasicPerformancePay(staffPayrollImportVo.getBasicPerformancePay());
                compensationStaffpayroll.setIncentivizedPerformancePay(staffPayrollImportVo.getIncentivizedPerformancePay());
                compensationStaffpayroll.setBasicPerformanceAward(staffPayrollImportVo.getBasicPerformanceAward());
                compensationStaffpayroll.setOneChildCare(staffPayrollImportVo.getOneChildCare());
                compensationStaffpayroll.setHousingSubsidies(staffPayrollImportVo.getHousingSubsidies());
                compensationStaffpayroll.setOvertimePay(staffPayrollImportVo.getOvertimePay());
                compensationStaffpayroll.setWagesPayable(staffPayrollImportVo.getWagesPayable());

                //实扣数
                compensationStaffpayroll.setActualDeduction(staffPayrollImportVo.getActualDeduction());

                //实发数
                compensationStaffpayroll.setActualSalary(staffPayrollImportVo.getActualSalary());

                //实扣工资浮动项详情
                List<CompensationDeductionAmountSettings> listDeductionAmountSettings = listDeductionAmountSettingsCpoy;
                for (CompensationDeductionAmountSettings listDeductionAmountSetting : listDeductionAmountSettings) {
                    if (("养老保险").equals(listDeductionAmountSetting.getDeductionsType())) {
                        listDeductionAmountSetting.setCost(staffPayrollImportVo.getEndowmentInsurance());
                    } else if (("职业年金").equals(listDeductionAmountSetting.getDeductionsType())) {
                        listDeductionAmountSetting.setCost(staffPayrollImportVo.getOccupationalCnnuity());
                    } else if (("医疗保险").equals(listDeductionAmountSetting.getDeductionsType())) {
                        listDeductionAmountSetting.setCost(staffPayrollImportVo.getMedicalInsurance());
                    } else if (("失业保险").equals(listDeductionAmountSetting.getDeductionsType())) {
                        listDeductionAmountSetting.setCost(staffPayrollImportVo.getUnemploymentInsurance());
                    } else if (("住房公积金").equals(listDeductionAmountSetting.getDeductionsType())) {
                        listDeductionAmountSetting.setCost(staffPayrollImportVo.getHousingProvidentFund());
                    } else if (("个人所得税").equals(listDeductionAmountSetting.getDeductionsType())) {
                        listDeductionAmountSetting.setCost(staffPayrollImportVo.getIndividualInComeTax());
                    } else if (("工会费").equals(listDeductionAmountSetting.getDeductionsType())) {
                        listDeductionAmountSetting.setCost(staffPayrollImportVo.getLaborDues());
                    } else if (("扣病假工资").equals(listDeductionAmountSetting.getDeductionsType())) {
                        listDeductionAmountSetting.setCost(staffPayrollImportVo.getDeductionSickPay());
                    } else if (("扣事假工资").equals(listDeductionAmountSetting.getDeductionsType())) {
                        listDeductionAmountSetting.setCost(staffPayrollImportVo.getDeductionPersonalLeaveSalary());
                    } else if (("扣哺乳假工资").equals(listDeductionAmountSetting.getDeductionsType())) {
                        listDeductionAmountSetting.setCost(staffPayrollImportVo.getDeductionNursingLeaveWages());
                    }
                }

                if (!staffPayrollImportVo.getEmployeeType().equals("在编人员")) {
                    for (CompensationDeductionAmountSettings listDeductionAmountSetting : listDeductionAmountSettings) {
                        if (("职业年金").equals(listDeductionAmountSetting.getDeductionsType())) {
                            listDeductionAmountSettings.remove(listDeductionAmountSetting);
                            break;
                        }
                    }
                }

                //将浮动项目数组对象转换为字符串存储数据库
                compensationStaffpayroll.setDeductionsPart(JSON.toJSONString(listDeductionAmountSettings));

                this.insertCompensationStaffpayroll(compensationStaffpayroll);
                successNum++;
                Num++;
                successMsg.append("<br/>" + "数据：" + successNum + "、姓名:" + staffPayrollImportVo.getNickName() + "，工资导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + "第" + Num + "行,导入失败。请检查是否准确填写";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，部分导入失败！本次导入Excel数据共" + totalNum + "条，其中成功导入" + successNum + "条" + ",共 " + failureNum + " 条数据格式不正确导入失败（请另外下载新模板将失败数据重新导入），错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！本次导入Excel数据共" + totalNum + "条，" + "其中，共 " + successNum + " 条成功导入，数据如下：");
        }
        return successMsg.toString();
    }

    //计算workOvertime加班费
    public BigDecimal calculateOvertimePay(Map<String, String> OvertimePay) {
        BigDecimal sum = new BigDecimal("0");
        //拿map里所有工资
        if (StringUtils.isNotEmpty(OvertimePay)) {
            BigDecimal a = new BigDecimal(OvertimePay.get("workOvertime_base_pay"));
            BigDecimal b = new BigDecimal(OvertimePay.get("workOvertime_base_performance_pay"));
            BigDecimal c = new BigDecimal(OvertimePay.get("workOvertime_incentive_performance_pay"));
            //四舍五入
            a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
            b = b.setScale(2, BigDecimal.ROUND_HALF_UP);
            c = c.setScale(2, BigDecimal.ROUND_HALF_UP);

            sum = sum.add(a);
            sum = sum.add(b);
            sum = sum.add(c);
        }
        return sum;
    }

    //计算lessen:哺乳假\事假\病假
    public BigDecimal calculateLessen(Map<String, String> lessen) {
        BigDecimal sum = new BigDecimal("0");
        //拿map里所有工资
        if (StringUtils.isNotEmpty(lessen)) {
            BigDecimal a = new BigDecimal(lessen.get("lessen_base_pay"));
            BigDecimal b = new BigDecimal(lessen.get("lessen_base_performance_pay"));
            BigDecimal c = new BigDecimal("0");
            if (StringUtils.isNotEmpty(lessen.get("lessen_incentive_performance_pay"))) {
                c = new BigDecimal(lessen.get("lessen_incentive_performance_pay"));
            }
            //四舍五入
            a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
            b = b.setScale(2, BigDecimal.ROUND_HALF_UP);
            c = c.setScale(2, BigDecimal.ROUND_HALF_UP);

            sum = sum.add(a);
            sum = sum.add(b);
            sum = sum.add(c);
        }
        return sum;
    }

}
